package com.tensquare.user.iterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.tensquare.dto.Result;
import com.tensquare.dto.StatusCode;
import com.tensquare.util.JwtUtil;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;

@Component
public class JwtIterceptor extends HandlerInterceptorAdapter{
	
	@Autowired
	private JwtUtil jwtUtil;
	

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
		
		//在这里解析token，把生成好的Claims放入请求中
		
		//获取token
		String auth = request.getHeader("Authorization");
		System.out.println("auth:"+auth);
		
		//解析token
		Claims parseJWT = null;
		if(StringUtils.isNotBlank(auth)&&auth.startsWith("Bearer ")) {
			try {
				parseJWT = jwtUtil.parseJWT(auth.substring(7));
			} catch (ExpiredJwtException e) {
				System.out.println("token过期了："+e.getMessage());
			} catch (Exception e) {
				System.out.println("解析jwt异常："+e.getMessage());
			}
		}
		//查看用户是否是管理员
		if(parseJWT!=null && "admin".equals(parseJWT.get("roles"))) {
			request.setAttribute("admin_Claims", parseJWT);
		}
		
		if(parseJWT!=null && "user".equals(parseJWT.get("roles"))) {
			request.setAttribute("user_Claims", parseJWT);
		}
		
		//日志信息
		if(parseJWT!=null) {
			System.out.println("日志信息：======》 当前操作用户："+parseJWT.getId()+" ===>"+parseJWT.getSubject());
		}
		
		
		return super.preHandle(request, response, handler);
	}
	
	

}
